<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/30
 * Time: 1:07 PM
 */

namespace app\backend\modules\sys\services;

use app\common\exceptions\BizException;
use app\common\models\Theme;
use app\common\models\ThemeFile;

class ThemeService
{
    /**
     * 已安装模版列表
     * @param $params
     * @return mixed
     */
    public function getInstalledList(){
        $query = Theme::site()->select();
        $list = $query
            ->orderBy('id', 'desc')
            ->paginate(10);
        $list->map(function ($v){
            $v->type_desc = '';
            $type_desc_arr = [];
            if($v->is_pc){
                array_push($type_desc_arr,'PC');
            }
            if($v->is_h5){
                array_push($type_desc_arr,'H5');
            }
            $v->type_desc = implode('\\',$type_desc_arr);
        });
        return $list;
    }

    /**
     * 未安装模版列表
     * @return array
     */
    public function getUnInstalledList(){
        $themePath = config('app.theme_path');
        $themesDirs = scandir($themePath);

        $themeModel = Theme::site()->select(['theme'])
            ->get();
        $installedTheme = $themeModel->pluck('theme')->toArray();

        $themesDirs = array_diff($themesDirs, $installedTheme);

        $themes = [];
        foreach ($themesDirs as $dir) {
            $manifest = $themePath."/$dir/manifest.json";
            if (is_file($manifest)) {
                $manifest       = file_get_contents($manifest);
                $theme          = json_decode($manifest, true);
                unset($theme['files']);
                $theme['theme'] = $dir;
                $theme['is_pc_desc'] = '否';
                $theme['is_h5_desc'] = '否';
                if($theme['is_pc']){
                    $theme['is_pc_desc'] = '是';
                }
                if($theme['is_h5']){
                    $theme['is_h5_desc'] = '是';
                }
                array_push($themes, $theme);
            }
        }
        return $themes;
    }

    /**
     * 安装模版
     * @param $theme
     * @throws BizException
     */
    public function installTheme($theme){
        $themePath = config('app.theme_path');
        $manifest = $themePath."/$theme/manifest.json";
        if (is_file($manifest)) {
            $manifest = file_get_contents($manifest);
            $themeData = json_decode($manifest, true);
            $themeData['theme'] = $theme;
            $themeModel = new Theme();
            $themeModel->site_id = \YunCms::siteId();
            $themeModel->name = $themeData['name'];
            $themeModel->theme = $themeData['theme'];
            $themeModel->version = $themeData['version'];
            $themeModel->description = $themeData['description'];
            if($themeModel->save()){
                $themeId = $themeModel['id'];
                $files = $themeData['files'];
                $now = time();
                $insertDataArr = [];
                foreach ($files as $v){
                    $configFile = $themePath.'/'.$theme.'/'.$v['config'];
                    if(is_file($configFile)){
                        $config = file_get_contents($configFile);
                        $configData = json_decode($config, true);
                        $insertData = [];
                        $insertData['site_id'] = \YunCms::siteId();
                        $insertData['theme_id'] = $themeId;
                        $insertData['name'] = $configData['name'];
                        $insertData['type'] = $configData['type'];
                        $insertData['file'] = $v['file'];
                        $insertData['description'] = $configData['description'];
                        $insertData['configs'] = json_encode($configData['configs']);
                        $insertData['created_at'] = $now;
                        array_push($insertDataArr,$insertData);
                    }else{
                        throw new BizException($v['config']."配置文件不存在");
                    }
                }
                if(count($insertDataArr)>0){
                    ThemeFile::insert($insertDataArr);
                }else{
                    \Log::debug(__CLASS__.'installTheme $insertDataArr为空');
                }
            }else{
                throw new BizException("模版安装失败，请稍后重试");
            }
        } else {
            throw new BizException("主配置文件不存在");
        }
    }
    /**
     * 返回按类型分组的默认的模版文件
     * @return array
     */
    public function getDefaultTypeFiles(){
        $themeList = Theme::site()->select()
            ->where('status',Theme::STATUS_NORMAL)
            ->where('is_default',Theme::STATUS_YES)
            ->with(['themeFiles' => function ($query) {
                return $query->select(['id','site_id','theme_id','name','file_name','type','file']);
            }])
            ->get();
        $res['pc'] = [];
        $res['h5'] = [];
        if($themeList){
            foreach ($themeList as $v){
                if($v['themeFiles']){
                    foreach ($v['themeFiles'] as $val){
                        $val['theme_name'] = $v['name'];
                        if($v['type']==Theme::TYPE_PC || $v['type']==Theme::TYPE_ALL){
                            if(!$res['pc'][$val['type']]){
                                $res['pc'][$val['type']] = [];
                            }
                            array_push($res['pc'][$val['type']],$val);
                        }
                        if($v['type']==Theme::TYPE_H5 || $v['type']==Theme::TYPE_ALL){
                            if(!$res['h5'][$val['type']]){
                                $res['h5'][$val['type']] = [];
                            }
                            array_push($res['h5'][$val['type']],$val);
                        }
                    }
                }
            }
        }
        foreach (ThemeFile::$allTypes as $v){
            if(!$res['pc'][$v]){
                //使用的模版不存在的类型，默认空数组
                $res['pc'][$v] = [];
            }
            if(!$res['h5'][$v]){
                //使用的模版不存在的类型，默认空数组
                $res['h5'][$v] = [];
            }
        }
        return $res;
    }
    /**
     * 返回按类型分组的正在使用的模版文件
     * @return array
     */
    public function getUsedTypeFiles(){
        $themeList = Theme::site()->select()
            ->where('status',Theme::STATUS_NORMAL)
            ->with(['themeFiles' => function ($query) {
                return $query->select(['id','site_id','theme_id','name','file_name','type','file']);
            }])
            ->get();
        $res['pc'] = [];
        $res['h5'] = [];
        if($themeList){
            foreach ($themeList as $v){
                if($v['themeFiles']){
                    foreach ($v['themeFiles'] as $val){
                        $val['theme_name'] = $v['name'];
                        if($v['type']==Theme::TYPE_PC || $v['type']==Theme::TYPE_ALL){
                            if(!$res['pc'][$val['type']]){
                                $res['pc'][$val['type']] = [];
                            }
                            array_push($res['pc'][$val['type']],$val);
                        }
                        if($v['type']==Theme::TYPE_H5 || $v['type']==Theme::TYPE_ALL){
                            if(!$res['h5'][$val['type']]){
                                $res['h5'][$val['type']] = [];
                            }
                            array_push($res['h5'][$val['type']],$val);
                        }
                    }
                }
            }
        }
        foreach (ThemeFile::$allTypes as $v){
            if(!$res['pc'][$v]){
                //使用的模版不存在的类型，默认空数组
                $res['pc'][$v] = [];
            }
            if(!$res['h5'][$v]){
                //使用的模版不存在的类型，默认空数组
                $res['h5'][$v] = [];
            }
        }
        return $res;
    }

}